from PyPDF2 import PdfFileReader, PdfFileWriter
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
import io

def compress_pdf(input_path, output_path):
    # 创建一个PDF读取器对象
    pdf_reader = PdfFileReader(input_path)
    pdf_writer = PdfFileWriter()

    # 遍历每一页，压缩内容
    for page_num in range(pdf_reader.getNumPages()):
        page = pdf_reader.getPage(page_num)
        packet = io.BytesIO()
        can = canvas.Canvas(packet, pagesize=letter)
        can.save()
        packet.seek(0)
        new_pdf = PdfFileReader(packet)
        page.mergePage(new_pdf.getPage(0))
        pdf_writer.addPage(page)

    # 写入压缩后的PDF
    with open(output_path, 'wb') as output_pdf:
        pdf_writer.write(output_pdf)

# 使用示例
input_pdf = '1.pdf'  # 替换为你的输入PDF路径
output_pdf = '2.pdf'  # 替换为你的输出PDF路径
compress_pdf(input_pdf, output_pdf)
